"use client";

import * as React from "react";
import { Check, ChevronsUpDown, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandList,
  CommandItem,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Badge } from "@/components/ui/badge";

export default function ComboboxMultiGroupSelector({
  options, // 选项数据，格式为 [{ label, value, children: [{ label, value }] }]
  value = [], // 当前选中的值，格式为 [{ parent, child }]
  onChange, // 值变化时的回调
  placeholder = "选择...",
  emptyText = "无数据",
  searchPlaceholder = "搜索...",
}) {
  const [open, setOpen] = React.useState(false);
  const [searchValue, setSearchValue] = React.useState("");

  // 获取选中项的标签
  const getSelectedLabel = (parentValue, childValue) => {
    const parent = options.find((opt) => opt.value === parentValue);
    if (!parent) return "";
    const child = parent.children?.find((child) => child.value === childValue);
    if (!child) return parent.label;
    return `${parent.label} / ${child.label}`;
  };

  // 检查是否已选中
  const isSelected = (parentValue, childValue) => {
    return value.some(
      (v) => v.parent === parentValue && v.child === childValue
    );
  };

  // 修改处理选择的逻辑
  const handleSelect = (parentValue, childValue) => {
    const newValue = [...value];
    const existingIndex = newValue.findIndex(
      (v) => v.parent === parentValue && v.child === childValue
    );

    if (existingIndex > -1) {
      // 如果已选中，则移除
      newValue.splice(existingIndex, 1);
    } else {
      // 移除同组中的其他选项
      const groupIndex = newValue.findIndex((v) => v.parent === parentValue);
      if (groupIndex > -1) {
        newValue.splice(groupIndex, 1);
      }
      // 添加新选项
      newValue.push({ parent: parentValue, child: childValue });
    }

    onChange?.(newValue);

    setTimeout(() => {
      setOpen(false);
    }, 100);
  };

  // 移除选中项
  const handleRemove = (parentValue, childValue) => {
    const newValue = value.filter(
      (v) => !(v.parent === parentValue && v.child === childValue)
    );
    onChange?.(newValue);
  };

  return (
    <div className="flex flex-col gap-2">
    {/* // 这个 modal 是用来阻止点击穿透的，但是会导致 Command 无法聚焦 */}
      <Popover open={open} onOpenChange={setOpen} modal={true}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            role="combobox"
            aria-expanded={open}
            className="w-full justify-between min-h-[2.5rem] h-auto"
          >
            <div className="flex justify-between w-full items-center">
              <div className="flex flex-wrap gap-2 flex-1 py-1">
                {value.length === 0 ? (
                  <span className="text-muted-foreground">{placeholder}</span>
                ) : (
                  value.map(({ parent, child }) => (
                    <Badge
                      key={`${parent}-${child}`}
                      variant="secondary"
                      className="flex items-center gap-1"
                    >
                      {getSelectedLabel(parent, child)}
                      <X
                        className="h-3 w-3 cursor-pointer"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleRemove(parent, child);
                        }}
                      />
                    </Badge>
                  ))
                )}
              </div>
              <ChevronsUpDown className="h-4 w-4 shrink-0 opacity-50 ml-2" />
            </div>
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
          <Command
            className="w-full"
            filter={(value, search) => {
              // 自定义搜索逻辑
              const parentLabel = options.find(
                parent => parent.children?.some(child => `${parent.value}-${child.value}` === value)
              )?.label || "";

              const childLabel = value.split('-')[1];
              const item = options
                .find(parent => parent.children?.some(child => child.value === childLabel))
                ?.children?.find(child => child.value === childLabel)?.label || "";

              return parentLabel.toLowerCase().includes(search.toLowerCase()) ||
                     item.toLowerCase().includes(search.toLowerCase());
            }}
          >
            <CommandInput
              placeholder={searchPlaceholder}
              value={searchValue}
              onValueChange={setSearchValue}
              className="h-9"
            />
            <CommandList>
              <CommandEmpty className="py-2 px-4 text-sm">{emptyText}</CommandEmpty>
              {options.map((parent) => (
                <CommandGroup
                  key={parent.value}
                  heading={parent.label}
                  className="overflow-hidden"
                >
                  {parent.children?.map((child) => (
                    <CommandItem
                      key={`${parent.value}-${child.value}`}
                      value={`${parent.value}-${child.value}`}
                      onSelect={() => handleSelect(parent.value, child.value)}
                      className="px-8 cursor-pointer"
                    >
                      <div className="flex items-center space-x-2">
                        <Check
                          className={cn(
                            "h-4 w-4",
                            isSelected(parent.value, child.value)
                              ? "opacity-100"
                              : "opacity-0"
                          )}
                        />
                        <span>{child.label}</span>
                      </div>
                    </CommandItem>
                  ))}
                </CommandGroup>
              ))}
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>

    </div>
  );
}
